using System.Data;

namespace DbVisualizer
{
    internal class DataTableFactory : IDataTableFactory
    {
        public DataTable Create(IDataReader dataReader)
        {
            var table = new DataTable { RemotingFormat = SerializationFormat.Binary };

            CreateColumns(dataReader, table);

            while (dataReader.Read())
            {
                var row = table.NewRow();

                for (var colIndex = 0; colIndex <= dataReader.FieldCount - 1; colIndex++)
                {
                    row[colIndex] = dataReader[colIndex];
                }
                table.Rows.Add(row);
            }

            return table;
        }

        private static void CreateColumns(IDataRecord reader, DataTable table)
        {
            for (var colIndex = 0; colIndex <= reader.FieldCount - 1; colIndex++)
            {
                table.Columns.Add(reader.GetName(colIndex));
            }
        }
    }
}